//
//  GoToCongMoneyVC.m
//  CenturyCity
//
//  Created by beisheng03 on 2018/1/18.
//  Copyright © 2018年 beisheng. All rights reserved.
//

#import "GoToCongMoneyVC.h"
#import "KeepCallsPayCell.h"
#import "KeepCallSectionHeader.h"
#import "KeepCallBottomView.h"
#import "CongMoneyFieldCell.h"
#import <WXApi.h>
#import <AlipaySDK/AlipaySDK.h>
@interface GoToCongMoneyVC ()

@property (nonatomic, strong) KeepCallBottomView *footerView;

@property (nonatomic, strong) GetMoneyInfoModel *infoModel;

@end

@implementation GoToCongMoneyVC



- (GetMoneyInfoModel *)infoModel{
    
    if (!_infoModel) {
        
        _infoModel = [[GetMoneyInfoModel alloc]init];
        
        _infoModel.alipay = @"1";
        
        _infoModel.wechatPay = @"0";
        
    }
    
    
    
    return _infoModel;
}


- (KeepCallBottomView *)footerView{
    
    if (!_footerView) {
        
        KeepCallBottomView *temp = (KeepCallBottomView *)[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([KeepCallBottomView class]) owner:nil options:nil].firstObject;
        
        [temp.topBtn setTitle:@"确认充值" forState:UIControlStateNormal];
        [temp.topBtn setTitle:@"确认充值" forState:UIControlStateHighlighted];
        
        [temp.topBtn addTarget:self action:@selector(payMoney) forControlEvents:UIControlEventTouchUpInside];
        
        _footerView = temp;
        
        [self.view addSubview:temp];
        
    }
    
    return _footerView;
}


- (void)payMoney{
    
    
    [self.view endEditing:YES];
    

    
    if (self.infoModel.money == nil) {
        
        [self showInformation:@"请输入提现金额"];
        
        return;
    }
    
    
    //判断是否是纯数字
    
    if( [self isPureInt:self.infoModel.money] || [self isPureFloat:self.infoModel.money])
        
    {
        
        
        if (!(self.infoModel.money.floatValue > 0)) {
            
            [self showInformation:@"输入金额非法"];
            
            return;
        }
        

        
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        parameters[@"recharge_money"] = self.infoModel.money;
        parameters[@"uid"] = myViewModel.user.uid;
        
        [SVProgressHUD showWithStatus:@"订单确认中..."];
        MJWeakSelf;
        [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"Member/recharge" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
            
            if (!error) {
                
//                MYJSONSTR
                
                
                [weakSelf lastPayWitPayment:responseObject[@"data"][@"pay_rmb"] outTradeNo:responseObject[@"data"][@"out_trade_no"]];
                
                
            } else {
                
                
                [SVProgressHUD showInfoWithStatus:error.domain];
            }
        }];
        
        
    }else{
        
        
        [self showInformation:@"输入金额非法"];
        
        
        
        
        
    }
    
    
    
    
}



- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    
    
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    
    
    
    
}

- (void)showInformation:(NSString *)str{
    
    UIAlertController *contr = [UIAlertController alertControllerWithTitle:nil message:str preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    
    
    //    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    //
    //
    //    }];
    //
    //
    //    [contr addAction:action2];
    [contr addAction:action1];
    
    [self presentViewController:contr animated:YES completion:nil];
    
    
    
    
}




- (BOOL)isPureInt:(NSString*)string{
    
    NSScanner* scan = [NSScanner scannerWithString:string];
    
    int val;
    
    return [scan scanInt:&val] && [scan isAtEnd];
    
}


//判断是否为浮点形：

- (BOOL)isPureFloat:(NSString*)string{
    
    NSScanner* scan = [NSScanner scannerWithString:string];
    
    float val;
    
    return [scan scanFloat:&val] && [scan isAtEnd];
    
}




- (void)lastPayWitPayment:(NSString *)payment outTradeNo:(NSString *)trade{
    //    ?out_trade_no=&pay_type=2&payment=0.01
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"payment"] = payment;
    parameters[@"out_trade_no"] = trade;
    
    if ([self.infoModel.alipay isEqualToString:@"1"]) {
        
        parameters[@"pay_type"] = @"2";
        
        [self AlipayPayWith:parameters];
        
    } else {
        
        parameters[@"pay_type"] = @"1";
        
        [self wachatPay:parameters];
        
    }
    
    
    
}



- (void)AlipayPayWith:(NSMutableDictionary *)parameters{
    
    
    
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"Pay/pay_order" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        
        if (!error) {
            
            [SVProgressHUD dismiss];
            
            [[AlipaySDK defaultService] payOrder:responseObject[@"data"] fromScheme:@"com.beisheng.feifubao" callback:^(NSDictionary *resultDic) {
                
                
                //                NSLog(@"reslut = %@",resultDic);
                
            }];
            
            
        } else {
            
            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
        
        
    }];
    
    
    
}

- (void)wachatPay:(NSMutableDictionary *)parameters{
    
    
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"Pay/pay_order" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        
        if (!error) {
            
            [SVProgressHUD dismiss];
            
            //            MYJSONSTR;
            
            [self WXPayWithDic:responseObject[@"data"]];
            
            
        } else {
            
            
            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
        
        
    }];
    
    
    
    
    
    
    
}



- (void)WXPayWithDic:(NSDictionary *)dic{
    
    //需要创建这个支付对象
    PayReq *req   = [[PayReq alloc] init];
    //由用户微信号和AppID组成的唯一标识，用于校验微信用户
    req.openID = dic[@"appid"];
    
    // 商家id，在注册的时候给的
    req.partnerId = dic[@"partnerid"];
    
    // 预支付订单这个是后台跟微信服务器交互后，微信服务器传给你们服务器的，你们服务器再传给你
    req.prepayId  = dic[@"prepayid"];
    
    // 根据财付通文档填写的数据和签名
    //这个比较特殊，是固定的，只能是即req.package = Sign=WXPay
    req.package   = dic[@"pkg"];
    
    // 随机编码，为了防止重复的，在后台生成
    req.nonceStr  = dic[@"noncestr"];
    
    // 这个是时间戳，也是在后台生成的，为了验证支付的
    NSString * stamp = dic[@"timestamp"];
    
    req.timeStamp = stamp.intValue;
    
    // 这个签名也是后台做的
    req.sign = dic[@"sign"];
    
    //发送请求到微信，等待微信返回onResp
    [WXApi sendReq:req];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"充值";
    
    self.tableView.tableFooterView = self.footerView;
    
    [self.tableView registerClass:[BaseTableViewCell class] forCellReuseIdentifier:[BaseTableViewCell identifierStr]];

    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([KeepCallsPayCell class]) bundle:nil] forCellReuseIdentifier:[KeepCallsPayCell identifierStr]];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([KeepCallSectionHeader class]) bundle:nil] forHeaderFooterViewReuseIdentifier:[KeepCallSectionHeader identifierStr]];
    

    
        [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CongMoneyFieldCell class]) bundle:nil] forCellReuseIdentifier:[CongMoneyFieldCell identifierStr]];
    
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(WXApiDidSuccessNotification) name:WXApiDidSuccessNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(WXApiDidFailNotification) name:WXApiDidFailNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(AlipayDidSuccessNotification) name:AlipayDidSuccessNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(AlipayDidFailNotification) name:AlipayDidFailNotification object:nil];
}




- (void)WXApiDidSuccessNotification{
    
    [SVProgressHUD showSuccessWithStatus:@"支付成功!"];
    
    [self.navigationController performSelector:@selector(popViewControllerAnimated:) withObject:@1 afterDelay:2.0];
    
}

- (void)WXApiDidFailNotification{
    
    [SVProgressHUD showInfoWithStatus:@"支付失败!"];
    
}

- (void)AlipayDidSuccessNotification{
    
    [SVProgressHUD showSuccessWithStatus:@"支付成功!"];
    
    [self.navigationController performSelector:@selector(popViewControllerAnimated:) withObject:@1 afterDelay:2.0];
    
}

- (void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    
    NSLog(@"fdsfdsfsfdsf333");
}


- (void)AlipayDidFailNotification{
    
    
    NSLog(@"fdsfdsfsfdsf33344444");

    
    [SVProgressHUD showInfoWithStatus:@"支付失败!"];
    
    
}


- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    
    if (section == 0) {
        
        
        return 1;
    } else {
        return 3;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.section == 0) {
        
        CongMoneyFieldCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[CongMoneyFieldCell identifierStr]];
        
        tableCell.model = self.infoModel;
        
        
        return tableCell;
        
        
    } else {
        
        if (indexPath.row == 2) {
            
            BaseTableViewCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[BaseTableViewCell identifierStr]];
            
            return tableCell;
            
        } else {
            
            KeepCallsPayCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[KeepCallsPayCell identifierStr]];
            
            tableCell.index = indexPath;
            
            tableCell.model = self.infoModel;
            
            
            return tableCell;
        }
    }
    
    
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        return 90;
        
        
    } else {
        
        if (indexPath.row == 2) {
            return 0;
        } else {
            return 72;
        }
        
        
    }
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return 0;
    } else {
        return 44;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        
        return [[UIView alloc]init];
        
    } else {
        
        KeepCallSectionHeader *view = (KeepCallSectionHeader *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:[KeepCallSectionHeader identifierStr]];
        
        return view;
    }
    
    
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    [self.view endEditing:YES];
    
    
    if (indexPath.section == 1) {
        
        if (indexPath.row == 0) {
            
            if ([self.infoModel.alipay isEqualToString:@"1"]) {
                
                return;
                
            } else {
                
                self.infoModel.alipay = @"1";
                self.infoModel.wechatPay = @"0";
                
            }
            
            
        } else {
            
            if ([self.infoModel.wechatPay isEqualToString:@"1"]) {
                
                return;
                
            } else {
                
                self.infoModel.wechatPay = @"1";
                self.infoModel.alipay = @"0";
                
            }
            
            
        }
        
        [self.tableView reloadData];
        
    }else{
        
      
        
        
    }
    
}


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    
    
    [self.view endEditing:YES];
}




@end
